from fastapi import FastAPI, Request

from myRequest import MyRequest
import threading
from mylog import logger

app = FastAPI()


# Endpoint to make an HTTP GET request with data
@app.get("/search")
async def make_http_request(request: Request):
    try:
        # Access query parameters from the request
        data_param = request.query_params.get("data", "")
        logger.error("search:" + data_param)
        data = MyRequest.search(data_param)
        # Include data_param in the logic or use it in the HTTP GET request if needed
        # For demonstration, just returning the data_param value
        return {"data": data}
    except Exception as e:
        return {"error": f"Error processing request: {e}"}


@app.get("/play")
async def play_url(request: Request):
    try:
        # Access query parameters from the request
        data_param = request.query_params.get("data", "")
        result = MyRequest.playList(data_param)
        result = MyRequest.playOne(result[0].get("url"))
        # Include data_param in the logic or use it in the HTTP GET request if needed
        # For demonstration, just returning the data_param value
        return {"data": result}
    except Exception as e:
        return {"error": f"Error processing request: {e}"}


@app.get("/play_list")
async def play_url(request: Request):
    try:
        # Access query parameters from the request
        data_param = request.query_params.get("data", "")
        result = MyRequest.playList2(data_param)
        # result = MyRequest.playOne(result[0].get("url"))
        # Include data_param in the logic or use it in the HTTP GET request if needed
        # For demonstration, just returning the data_param value
        return {"data": result}
    except Exception as e:
        return {"error": f"Error processing request: {e}"}


@app.get("/play_one")
async def play_url(request: Request):
    try:
        # Access query parameters from the request
        data_param = request.query_params.get("data", "")
        title_param = request.query_params.get("title", "")
        # result = MyRequest.playList(data_param)
        result = MyRequest.playOne(data_param, title_param)
        # Include data_param in the logic or use it in the HTTP GET request if needed
        # For demonstration, just returning the data_param value
        return {"data": result}
    except Exception as e:
        return {"error": f"Error processing request: {e}"}


if __name__ == "__main__":
    import uvicorn

    MyRequest.Login()
    # 创建一个线程对象，将 my_task 函数作为目标传递给线程
    my_thread = threading.Thread(target=MyRequest.taskSchedule)

    # 启动线程
    my_thread.start()
    print("start")
    uvicorn.run(app, host="0.0.0.0", port=8000)
